﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FaceSharp.MVC.Code.Extensions
{
    public static class TimeSpanHelper
    {
        /// <summary>
        /// Converts the specified DateTime to its relative date.
        /// </summary>
        /// <param name="dateTime">The DateTime to convert.</param>
        /// <returns>A string value based on the relative date 
        /// of the datetime as compared to the current date.</returns>
        public static string ToRelativeDate(this DateTime dateTime)
        {
            TimeSpan timeSpan = DateTime.Now.Subtract(dateTime);


            // span is less than or equal to 60 seconds, measure in seconds.

            if (timeSpan <= TimeSpan.FromSeconds(60))
            {
                return timeSpan.Seconds + " seconds";
            }

            // span is less than or equal to 60 minutes, measure in minutes.

            if (timeSpan <= TimeSpan.FromMinutes(60))
            {
                return timeSpan.Minutes > 1 ? timeSpan.Minutes + " minutes" : "about a minute";
            }

            // span is less than or equal to 24 hours, measure in hours.

            if (timeSpan <= TimeSpan.FromHours(24))
            {
                return timeSpan.Hours > 1 ? timeSpan.Hours + " hours" : "about an hour";
            }

            // span is less than or equal to 30 days (1 month), measure in days.

            if (timeSpan <= TimeSpan.FromDays(30))
            {
                return timeSpan.Days > 1 ? timeSpan.Days + " days" : "about a day";
            }

            // span is less than or equal to 365 days (1 year), measure in months.

            if (timeSpan <= TimeSpan.FromDays(365))
            {
                return (timeSpan.Days / 30) > 1 ? timeSpan.Days / 30 + " months" : "about a month";
            }


            // span is greater than 365 days (1 year), measure in years.

            return timeSpan.Days > 365 ? timeSpan.Days / 365 + " years" : "one year";
        }
    }
}